<template>
  <div class="login-page">
    <div class="login-container">
      <h2><span>{{ isDoctor ? '医生' : '患者' }}</span>登录</h2>
      <el-form :model="form" :rules="rules" ref="loginForm" label-width="60px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名">
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号">
            <template #prefix>
              <el-icon><Iphone /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password>
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" class="login-button">登录</el-button>
        </el-form-item>
      </el-form>

      <p class="identity-toggle">
        <span class="link-text" @click="toggleIdentity">
          我是{{ isDoctor ? '患者' : '医生' }}
        </span>
      </p>
      <p class="register-link">
        还没有账号？<router-link to="/register">点击注册</router-link>
      </p>
    </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus'
import api from '@/api'
import { User, Iphone, Lock } from '@element-plus/icons-vue' // 导入 Element Plus 图标

export default {
  name: 'UserLogin',
  components: {
    User,
    Iphone,
    Lock,
  },
  data() {
    return {
      isDoctor: false,
      form: {
        name: '',
        phone: '',
        password: '',
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
      },
    }
  },

  methods: {
    handleLogin() {
      this.$refs.loginForm.validate(async (valid) => {
        if (!valid) return

        const params = {
          name: this.form.name,
          phone: this.form.phone,
          password: this.form.password,
        }
        const url = this.isDoctor ? '/doctor/login' : '/user/login'

        try {
          const response = await api.post(url, params)
          if (response.status === 200 && response.data.code === 200) {
            const user = response.data.data

            // 保存登录信息
            localStorage.setItem('isLogin', 'true')
            localStorage.setItem('userRole', this.isDoctor ? 'doctor' : 'patient')
            localStorage.setItem('token', response.data.token || 'dummy_token')
            localStorage.setItem('username', this.form.name)

            // ✅ 保存 userId
            if (user?.userId) {
              localStorage.setItem('userId', user.userId)
              console.log('保存的 userId:', user.userId)
            } else if (user?.id) {
              localStorage.setItem('userId', user.id)
              console.log('保存的 userId:', user.id)
            }

            ElMessage.success('登录成功！')
            this.$router.push('/home')
          } else {
            ElMessage.error('登录失败：' + (response.data.msg || '未知错误'))
          }
        } catch (error) {
          ElMessage.error('请求失败，请检查网络或接口')
        }
      })
    },

    toggleIdentity() {
      this.isDoctor = !this.isDoctor
      // 清空表单，提供更好的用户体验
      this.form.name = ''
      this.form.phone = ''
      this.form.password = ''
      this.$refs.loginForm.resetFields()
    }
  }
}
</script>

<style scoped>
/* 全屏背景 */
.login-page {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh; /* 确保占满整个视口高度 */
  background: linear-gradient(to top right, #add8e6, #87ceeb); /* 浅蓝色到天蓝色的渐变 */
  animation: background-animate 15s ease infinite; /* 添加背景动画 */
}

@keyframes background-animate {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}

/* 登录容器 */
.login-container {
  width: 360px; /* 稍微增大宽度 */
  padding: 40px; /* 增大内边距 */
  background-color: rgba(255, 255, 255, 0.95); /* 半透明白色背景 */
  border-radius: 12px; /* 更大的圆角 */
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15); /* 更明显的阴影 */
  animation: slide-in 0.8s ease-out forwards; /* 登录框滑入动画 */
}

@keyframes slide-in {
  from {
    opacity: 0;
    transform: translateY(-30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

h2 {
  text-align: center;
  margin-bottom: 30px; /* 增大标题与表单的间距 */
  font-size: 28px; /* 标题字号 */
  color: #333; /* 标题颜色 */
  font-weight: 600; /* 标题字重 */
}

h2 span {
  color: #409EFF; /* 角色文字颜色与Element Plus主色调一致 */
}

/* Element Plus 表单项和输入框样式调整 */
.el-form-item {
  margin-bottom: 22px; /* 调整表单项间距 */
}

.el-input {
  border-radius: 6px; /* 输入框圆角 */
}

/* 按钮样式 */
.login-button {
  width: 100%;
  border-radius: 8px; /* 按钮圆角 */
  height: 45px; /* 按钮高度 */
  font-size: 16px; /* 按钮文字大小 */
  box-shadow: 0 4px 10px rgba(64, 158, 255, 0.3); /* 按钮阴影 */
  transition: all 0.3s ease; /* 添加过渡效果 */
}

.login-button:hover {
  transform: translateY(-2px); /* 鼠标悬停时上浮 */
  box-shadow: 0 6px 15px rgba(64, 158, 255, 0.4);
}

/* 身份切换链接 */
.identity-toggle {
  margin-top: 25px; /* 调整间距 */
  text-align: center;
  font-size: 14px;
  color: #666;
}

.link-text {
  color: #409EFF;
  cursor: pointer;
  text-decoration: underline;
  margin-left: 5px; /* 调整与文字的间距 */
  font-weight: 500;
  transition: color 0.3s ease;
}

.link-text:hover {
  color: #66b1ff;
}

/* 注册链接 */
.register-link {
  text-align: center;
  margin-top: 15px;
  font-size: 14px;
  color: #666;
}

.register-link a {
  color: #409EFF;
  text-decoration: none;
  font-weight: 500;
  transition: color 0.3s ease;
}

.register-link a:hover {
  color: #66b1ff;
  text-decoration: underline;
}
</style>